package com.asm.demo;


import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.util.TraceClassVisitor;

import java.io.*;

/**
 * Created by james on 16/2/25.
 * 通过asm生成类的字节码
 */
public class ClassWriterDemo {

    public static void main(String[] args) {
        //生成一个类只需要ClassWriter组件即可
        ClassWriter cw = new ClassWriter(0);//0???



        //通过visit方法确定类的头部信息
        cw.visit(Opcodes.V1_6,Opcodes.ACC_PUBLIC+Opcodes.ACC_ABSTRACT+Opcodes.ACC_INTERFACE,"com/asm/demo/Comparable",null,"java/lang/Object",new String[]{"com/asm/demo/Mesurable"});
        //定义类的属性
        cw.visitField(Opcodes.ACC_PUBLIC+Opcodes.ACC_FINAL+Opcodes.ACC_STATIC,"LESS","I",null,new Integer(-1)).visitEnd();
        //定义类的方法
        cw.visitMethod(Opcodes.ACC_PUBLIC+Opcodes.ACC_ABSTRACT, "compareTo","(Ljava/lang/Object;)I", null, null).visitEnd();
        cw.visitEnd();//使cw类已经完成
        byte[] data = cw.toByteArray();
        File file = new File("./Comparable.class");
        try {
            FileOutputStream fout = new FileOutputStream(file);
            fout.write(data);
            fout.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
